#!/usr/bin/env php
<?php
/**
 * Generated from 'save_sources2file.in' on mié jun 15 11:00:03 COT 2011.
 *
 * Saves all submissions from the database. This can be used to later
 * restore them with 'restore_sources2db'.
 *
 * Things to fix:
 * - requires php 5.0 (due to file_put_contents)
 * - add logging that IS useful
 *
 * $Id: save_sources2file.in 3302 2010-08-09 18:39:20Z eldering $
 *
 * Part of the DOMjudge Programming Contest Jury System and licenced
 * under the GNU GPL. See README and COPYING for details.
 */
if ( isset($_SERVER['REMOTE_ADDR']) ) die ("Commandline use only");

require('/usr/local/domjudge/domserver/etc/domserver-static.php');
require(ETCDIR . '/domserver-config.php');

define('SCRIPT_ID', 'save_sources2file');
define('LOGFILE', LOGDIR.'/auxiliary.log');

require(LIBDIR . '/init.php');

setup_database_connection('jury');

$verbose = LOG_INFO;

$sourcesdir = getcwd();
if ( ! empty($_SERVER['argv'][1]) ) $sourcesdir = $_SERVER['argv'][1];

if ( !(is_dir($sourcesdir) && is_writable($sourcesdir)) ) {
	error("'$sourcesdir' is no directory or not writable");
}

logmsg(LOG_NOTICE, "started, sources dir = '" . $sourcesdir . "'");

$res = $DB->q('SELECT s.*, l.extension FROM submission s
               LEFT JOIN language l USING (langid)');

while( $row = $res->next() ) {

	$filename = implode('.',array('c'.$row['cid'],'s'.$row['submitid'],
	                              $row['teamid'],$row['probid'],$row['extension']));

	$filepath = $sourcesdir . '/' . $filename;
	file_put_contents($filepath, $row['sourcecode']);
	touch($filepath, strtotime($row['submittime']));

	logmsg(LOG_DEBUG, "saved file '$filename'");
}

logmsg(LOG_NOTICE, "finished");

exit;
